# -*- coding: utf-8 -*-

import sys
from .strutils import get_str_display_width


class Texttable(object):
    def __init__(self):
        self._colw = []
        self._rows = []

    def add_row(self, row):
        if not row:
            return

        self._rows.append(row)
        # 确定宽度
        if not self._colw:
            self._colw = [self._col_hint_width(col) for col in row]
        # 确定每个字段的宽度
        for i, col in enumerate(row):
            w = self._col_hint_width(col)
            self._colw[i] = max(w, self._colw[i])

    def add_rows(self, rows):
        for row in rows:
            self.add_row(row)

    def draw(self):
        if not self._rows:
            return

        for row in self._rows:
            for i, col in enumerate(row):
                s = str(col)
                sys.stdout.write(s)
                sys.stdout.write(
                    ' ' * (self._colw[i] - get_str_display_width(s)))
            sys.stdout.write('\n')

    @staticmethod
    def _col_hint_width(col):
        return get_str_display_width(str(col)) + 4
